package com.kingwang.study.spring.security.demo.security.token;

import lombok.Getter;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * Token认证执行成功后的Authentication对象
 */
public class TokenBasedAuthenticationResultToken extends AbstractAuthenticationToken {
    /**
     * 额外属性
     */
    @Getter
    private Map<String, String> attributes = new HashMap<>();

    @Getter
    private Object principal;

    @Getter
    private Object credentials;

    @Getter
    private String tokenType;

    @Getter
    private String token;

    public TokenBasedAuthenticationResultToken(Object principal, Object credentials,
                                               String tokenType, String token,
                                               Collection<? extends GrantedAuthority> authorities) {
        super(authorities);
        this.principal = principal;
        this.credentials = credentials;
        this.tokenType = tokenType;
        this.token = token;
        super.setAuthenticated(true);
    }

    @Override
    public Object getCredentials() {
        return this.credentials;
    }

    @Override
    public Object getPrincipal() {
        return this.principal;
    }

    @Override
    public void eraseCredentials() {
        super.eraseCredentials();
        this.credentials = null;
    }

    /**
     * 添加额外属性
     *
     * @param name
     * @param value
     */
    public void setAttribute(String name, String value) {
        this.attributes.put(name, value);
    }

    /**
     * 删除额外属性
     *
     * @param name
     */
    public void removeAttribute(String name) {
        this.attributes.remove(name);
    }

    /**
     * 获取额外属性
     *
     * @param name
     * @return
     */
    public String getAttribute(String name) {
        return this.attributes.get(name);
    }
}
